import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
    Form, Input, Button, Card, Select,Radio, Upload, Icon
} from 'antd';
import styles from '../../../routes/style.less';
import {message} from "antd/lib/index";
import constants from '../../../common/constants';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}
@connect(state => ({
    rule: state.brandEdit,
}))
@Form.create()
export default class BrandEdit extends PureComponent {
    state = {
        loading: false,
    };
    handleParentModalVisible = (e) => {
        this.props.handleModalVisible();
    }

    handleSubmit = (editType,brand_id,e) => {
        this.props.form.validateFieldsAndScroll((err, values) => {
            console.log(values);
            if (!err) {
                let user_id = '';
                const userInfoState = sessionStorage.getItem("userInfoState");
                if (userInfoState !== null) {
                    const {userInfo} = JSON.parse(userInfoState);
                    user_id = userInfo.user_id;
                }
                this.props.dispatch({
                    type: `brandEdit/${editType}`,
                    payload: {...values,brand_id: brand_id,add_user_id:user_id},
                    callback: (response) => {
                        if (response.result === 0) {
                            message.success('提交成功');
                            this.props.handleModalVisible();
                            this.props.handleModalSuccess(this.props.pagination);
                        } else {
                            message.success('提交失败');
                        }
                    }
                });
            }
        });
    }

    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl => this.setState({
                imageUrl,
                loading: false,
            }));
        }
    }
    normFile = (e) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && `${e.file.response[0].fileUrl}`;
    }

    render() {
        const {submitting, record, editType, brandSList} = this.props;
        const {getFieldDecorator, getFieldValue} = this.props.form;
        const formInitValue = editType === 'add' ? '' : record;
        const brand_id = editType === 'add' ? '' : record.brand_id;
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
                md: {span: 10},
            },
        };
        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };

        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传</div>
            </div>
        );

        const imageUrl = this.state.imageUrl;
        console.log(formInitValue.brand_logo);
        return (
            <Card bordered={false}>
                <Form
                    onSubmit={this.handleSubmit}
                    hideRequiredMark
                >
                    <FormItem
                        {...formItemLayout}
                        label="品牌名称"
                    >
                        {getFieldDecorator('brand_name', {
                            initialValue:  formInitValue.brand_name || '',
                            rules: [{
                                required: true, message: '请输入品牌名称',
                            }],
                        })(
                            <Input placeholder="品牌名称"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>品牌字母<em className={styles.optional}>（选填）</em></span>}
                    >
                        {getFieldDecorator('brand_letter', {
                            initialValue:  formInitValue.brand_letter || '',
                            rules: [{
                            }],
                        })(
                            <Input placeholder="品牌字母"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="Logo图片"
                    >
                        {getFieldDecorator('brand_logo', {
                            initialValue:  formInitValue.brand_logo || '',
                            getValueFromEvent: this.normFile,
                            rules: [{
                                required: true, message: '请上传Logo图片',
                            }],
                        })(
                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action={constants.fileServer}
                                // defaultFileList={formInitValue.brand_logo}
                                // beforeUpload={beforeUpload}
                                onChange={this.handleChange}
                            >
                                {
                                    !imageUrl ?
                                    formInitValue.brand_logo ? <img height="150" width="150" src={`${constants.imageUrlFix}${formInitValue.brand_logo}`} alt="" /> : uploadButton
                                    : <img src={imageUrl} alt="" height="150" width="150"/>
                                }

                            </Upload>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>品牌描述<em className={styles.optional}>（选填）</em></span>}
                    >
                        {getFieldDecorator('brand_desc', {
                            initialValue:  formInitValue.brand_desc || '',
                            rules: [{
                            }],
                        })(
                            <Input placeholder="品牌描述"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>品牌网址<em className={styles.optional}>（选填）</em></span>}
                    >
                        {getFieldDecorator('site_url', {
                            initialValue:  formInitValue.site_url || '',
                            rules: [{
                            }],
                        })(
                            <Input placeholder="品牌网址"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="顺序"
                    >
                        {getFieldDecorator('sort_order', {initialValue: formInitValue.sort_order || 100})(
                            <Input placeholder=""/>
                        )}<em className={styles.optional}>数字越大顺序越靠后</em>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="前台页面显示"
                    >
                        {getFieldDecorator('is_show', {
                            initialValue: !formInitValue.is_show ? 0 : 1,
                            rules: [{
                                required: true, message: '请选择',
                            }],
                        })(
                            <RadioGroup>
                                <Radio value={1}>显示</Radio>
                                <Radio value={0}>不显示</Radio>
                            </RadioGroup>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="是否删除"
                    >
                        {getFieldDecorator('is_delete', {
                            initialValue: !formInitValue.is_delete ? 0 : 1,
                            rules: [{
                                required: true, message: '请选择',
                            }],
                        })(
                            <RadioGroup>
                                <Radio value={1}>是</Radio>
                                <Radio value={0}>否</Radio>
                            </RadioGroup>
                        )}
                    </FormItem>
                    <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                        <Button type="primary" loading={submitting} onClick={this.handleSubmit.bind(this,editType,brand_id)}>
                            提交
                        </Button>
                        <Button style={{marginLeft: 8}} onClick={this.handleParentModalVisible}>取消</Button>
                    </FormItem>
                </Form>
            </Card>
        );
    }
}
